package com.cqc.rxjava01.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.cqc.rxjava01.Http.ApiConstant;
import com.cqc.rxjava01.Http.RetrofitHelper;
import com.cqc.rxjava01.Http.UserApi;
import com.cqc.rxjava01.Http.UserApiWrapper;
import com.cqc.rxjava01.R;
import com.cqc.rxjava01.entity.BaseResult;
import com.cqc.rxjava01.entity.CommonResult;
import com.cqc.rxjava01.entity.User;
import com.cqc.rxjava01.util.LogUtil;

import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by cui on 2017/8/16.
 * retrofit
 */

public class RetrofitActivity extends AppCompatActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
    }

    /**
     * 图片上传
     * @param view
     */
    public void rxJava09(View view) {
        User user = new User();
        user.setUsername("mike");
        user.setPassword("123456");

        UserApiWrapper.getInstance().login(user).subscribe(new Consumer<User>() {
            @Override
            public void accept(User user) throws Exception {
                LogUtil.d("accept=" + user.toString());
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtil.d(throwable.getMessage());
            }
        });
    }

    /**
     * 注册后登录 RxJava
     */
    public void rxJava08(View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        final UserApi userApi = retrofit.create(UserApi.class);

        User user = new User();
        user.setUsername("mike");
        user.setPassword("123456");

        userApi.register(user)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .doAfterNext(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        //注册后的一些操作，比如提示注册成功，可以登录
                        LogUtil.d("注册成功：" + user.toString());
                    }
                })
                .subscribeOn(Schedulers.io())
                .flatMap(new Function<User, ObservableSource<BaseResult>>() {
                    @Override
                    public ObservableSource<BaseResult> apply(User user) throws Exception {
                        LogUtil.d("flatMap：" + user.toString());
                        return userApi.login2(user);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult>() {
                    @Override
                    public void accept(BaseResult response) throws Exception {
                        LogUtil.d("登录成功：" + response.getData().toString());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtil.d("登录失败：" + throwable);
                    }
                });
    }

    /**
     * 注册后登录
     * 普通的写法
     */
    public void rxJava07(View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        UserApi userApi = retrofit.create(UserApi.class);

        register(userApi);
    }


    public void register(final UserApi userApi) {
        User user = new User();
        user.setUsername("mike");
        user.setPassword("123456");

        userApi.register(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        //注册成功
                        LogUtil.d("注册成功：" + user.toString());
                        login(userApi, user);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //注册失败
                        LogUtil.d("注册失败：" + throwable.getMessage());
                    }
                });
    }

    public void login(UserApi userApi, User user) {
        userApi.login2(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult>() {
                    @Override
                    public void accept(BaseResult response) throws Exception {
                        //登录成功
                        LogUtil.d("登录成功：" + response.getData().toString());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //登录失败
                        LogUtil.d("登录失败：" + throwable.getMessage());
                    }
                });
    }


    /**
     * transform2(@NonNull Observable<CommonResult<T>> observable)
     * @param view
     */
    public void rxJava06(View view) {
        User user = new User();
        user.setUsername("mike");
        user.setPassword("123456");

        UserApiWrapper.getInstance().login2(user).subscribe(new Consumer<User>() {
            @Override
            public void accept(User user) throws Exception {
                LogUtil.d("accept=" + user.toString());
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtil.d(throwable.getMessage());
            }
        });
    }


    /**
     * 参数为User，返回数据去掉msg success 接收User
     * transform(@NonNull Observable<R> observable)
     * @param view
     */
    public void rxJava05(View view) {
        User user = new User();
        user.setUsername("mike");
        user.setPassword("123456");

        UserApiWrapper.getInstance().login(user).subscribe(new Consumer<User>() {
            @Override
            public void accept(User user) throws Exception {
                LogUtil.d("accept=" + user.toString());
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtil.d(throwable.getMessage());
            }
        });
    }

    /**
     * 参数为User，返回CommonResult<User> 需要自己解析，获取User
     *
     * @param view
     */
    public void rxJava04(View view) {
        String username = "123456";
        String password = "123456";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        UserApi userApi = retrofit.create(UserApi.class);

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        userApi.login2(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult>() {
                    @Override
                    public void accept(BaseResult result) throws Exception {
                        LogUtil.d("接收,response" + result.getData().toString() + "，线程=" + Thread.currentThread().getName());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtil.d("Throwable=" + throwable.getMessage());
                    }
                });
    }

    /**
     * 参数为引用数据类型，返回CommonResult<T>，需要自己解析，获取T
     *
     * @param view
     */
    public void rxJava03(View view) {
        User user = new User();
        user.setUsername("mike");
        user.setPassword("123456");
        RetrofitHelper.createUserApi()
                .login4(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CommonResult<User>>() {
                    @Override
                    public void accept(CommonResult<User> result) throws Exception {
                        LogUtil.d("accept=" + result.getData().toString());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtil.d(throwable.getMessage());
                    }
                });
    }


    /**
     * 参数为基本数据类型，返回CommonResult  User 没有使用泛型
     *
     * @param view
     */
    public void rxJava02(View view) {
        String username = "123456";
        String password = "123456";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        UserApi userApi = retrofit.create(UserApi.class);

        userApi.login(username, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult>() {
                    @Override
                    public void accept(BaseResult result) throws Exception {
//                        LogUtil.d( "接收,response" + ((User)result.getData()).toString() + "，线程=" + Thread.currentThread().getName());
                        LogUtil.d("接收,response" + result.getData().toString() + "，线程=" + Thread.currentThread().getName());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtil.d("Throwable=" + throwable);
                    }
                });

    }

    /**
     * 基本使用
     * @param view
     */
    public void rxJava01(View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        UserApi userApi = retrofit.create(UserApi.class);

        //ScalarsConverterFactory
        Call<String> call = userApi.getAllOrders("18100000001");
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.body() == null) {
                    LogUtil.d("response == null");
                }
//                response.body();
                LogUtil.d("response=" + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                LogUtil.d("onFailure");
            }
        });


        //GsonConverterFactory
//        Call<ResultModel> call2 = userApi.getAllOrders2("18100000001");
//        call2.enqueue(new Callback<ResultModel>() {
//            @Override
//            public void onResponse(Call<ResultModel> call, Response<ResultModel> response) {
//                LogUtil.d( "response=" + response.body().getLoadResult());
//            }
//
//            @Override
//            public void onFailure(Call<ResultModel> call, Throwable t) {
//
//            }
//        });


    }
}
